package com.cabrida.livestar.pay;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cabrida.livestar.BaseActivity;
import com.cabrida.livestar.R;
import com.cabrida.livestar.config.Constants;
import com.cabrida.livestar.config.Global;
import com.cabrida.livestar.config.HttpHelp;
import com.cabrida.livestar.config.Urls;
import com.cabrida.livestar.model.BuyData;
import com.cabrida.livestar.model.JSONParser;
import com.cabrida.livestar.util.AliPayManager;
import com.cabrida.livestar.util.HttpUtils;
import com.cabrida.livestar.util.JsonUtils;
import com.cabrida.livestar.util.L;
import com.cabrida.livestar.util.MyUtils;
import com.cabrida.livestar.util.NetworkUtils;
import com.cabrida.livestar.util.Util;
import com.cabrida.livestar.view.CircleImageView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 充值
 */
public class PayActivity extends BaseActivity {
	public static final String TAG = PayActivity.class.getSimpleName();
	private ImageView iv_back;
	private TextView tv_title;
	private GridView gridView;
	private PayGvAdapter adapter;
	private CircleImageView iv_header;
	private TextView tv_account_num;
	private EditText et_pay_num;
	private TextView tv_pay_num;
	
	private LinearLayout ll_wx;
	private LinearLayout ll_ali;
	private String orderId;
	
	private final String type_wx="10";
	private final String type_ali="20";
	private String type;
	private IWXAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
		api.registerApp(Constants.SECRET);
	}
	
	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Intent intent = null;
            switch (msg.what) {
                case -1:
                    break;
                case 1:
                    break;
                case 2:
                    break;
            }
        }
    };
	

	/** 调用支付宝 *  */
	private void sendAli() {
		AliPayManager pm = new AliPayManager(this,  handler);
        pm.aliPay(orderId);
	}
	
	/** 调用微信 *  */
	private void sendWX() {
		String url = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android";
		try{
			byte[] buf = Util.httpGet(url);
			if (buf != null && buf.length > 0) {
				String content = new String(buf);
	        	JSONObject json = new JSONObject(content); 
				if(null != json && !json.has("retcode") ){
					PayReq req = new PayReq();
					//req.appId = "wxf8b4f85f3a794e77";  // 测试用appId
					req.appId			= json.getString("appid");
					req.partnerId		= json.getString("partnerid");
					req.prepayId		= json.getString("prepayid");
					req.nonceStr		= json.getString("noncestr");
					req.timeStamp		= json.getString("timestamp");
					req.packageValue	= json.getString("package");
					req.sign			= json.getString("sign");
					req.extData			= "app data"; // optional
					showToast("正常调起支付");
					// 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
					api.sendReq(req);
				}else{
					showToast("返回错误"+json.getString("retmsg"));
				}
			}else{
				showToast("服务器请求错误");
	        }
        }catch(Exception e){
        	showToast("异常："+e.getMessage());
        }
	}
	
	/** 获取订单数据
	 * type 10wx 20ali 30apple
	 *  */
	private void getOrderData(String cid,String amount) {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		params.put("type", type);
		params.put("cid", cid);
		params.put("amount", amount);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_PAY_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getOrderData", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							orderId = JsonUtils.getString(response, "data", "");
							if(type.equals(type_wx)){
								sendWX();
							}else {
								sendAli();
							}
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}

	/** 充值数据 */
	private void getPayList() {
		// TODO Auto-generated method stub
		RequestParams params = new RequestParams();
		params.put("udid", Global.U_id);
		params.put("token", Global.U_token);
		if (!NetworkUtils.isNetAvailable(context)) {
			showToast(R.string.no_network);
			return;
		}
		showProgress();
		HttpUtils.getClient().post(Urls.GET_BUY_URL, params,
				new JsonHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							JSONObject response) {
						dismissProgress();
						L.e(TAG, "getPayList", response.toString());
						int code = JsonUtils.getInt(response, "code", -1);
						if (code == HttpHelp.Succeed) {
							JSONArray data = JsonUtils.getJSONArray(response,
									"data", new JSONArray());
							ArrayList<BuyData> infoList = JSONParser
									.getFansBuyList(data);
							adapter.setData(infoList);
							adapter.notifyDataSetChanged();
						} else {
							JSONObject data = JsonUtils.getJSONObject(response,
									"data", new JSONObject());
							String message = JsonUtils.getString(data,
									"message", "");
							showToast(message);
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						dismissProgress();
						showToast(getResources().getString(R.string.fwq_error));
					}
				});
	}
	
	/** 刷新充值数量 */
	private void refreshPayNum(String num){
		tv_pay_num.setText(num);
	}
	
	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_pay);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_title = (TextView) findViewById(R.id.tv_title);
		gridView = (GridView) findViewById(R.id.gridView);
		iv_header = (CircleImageView) findViewById(R.id.iv_header);
		tv_account_num = (TextView) findViewById(R.id.tv_account_num);
		et_pay_num = (EditText) findViewById(R.id.et_pay_num);
		tv_pay_num = (TextView) findViewById(R.id.tv_pay_num);
		ll_wx = (LinearLayout) findViewById(R.id.ll_wx);
		ll_ali = (LinearLayout) findViewById(R.id.ll_ali);
	}

	@Override
	protected void initView() {
		// TODO Auto-generated method stub
		iv_back.setOnClickListener(this);
		ll_wx.setOnClickListener(this);
		ll_ali.setOnClickListener(this);
		tv_title.setText(getString(R.string.fans_pay));
		MyUtils.loadImg(Global.headPic, iv_header);
		tv_account_num.setText(Global.U_balance);
		adapter = new PayGvAdapter(context);
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				et_pay_num.setText("");
				BuyData data = (BuyData) arg0.getAdapter().getItem(arg2);
				ArrayList<BuyData> infoList = adapter.getData();
				for (int i = 0; i < infoList.size(); i++) {
					if (infoList.get(i).getC_id().toString()
							.equals(data.getC_id().toString())) {
						infoList.get(i).setSelect(!data.isSelect());
						refreshPayNum(infoList.get(i).getC_value().toString());
					} else {
						infoList.get(i).setSelect(false);
					}
				}
				adapter.setData(infoList);
				adapter.notifyDataSetChanged();
			}
		});
		et_pay_num.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				refreshPayNum(arg0.toString());
				ArrayList<BuyData> infoList = adapter.getData();
				for (int i = 0; i < infoList.size(); i++) {
					infoList.get(i).setSelect(false);
				}
				adapter.setData(infoList);
				adapter.notifyDataSetChanged();
			}
		});
		getPayList();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_back:
			this.finish();
			break;
		case R.id.ll_wx:
			{String cid = "";
			String amount = "";
			ArrayList<BuyData> infoList = adapter.getData();
			for (int i = 0; i < infoList.size(); i++) {
				if (infoList.get(i).isSelect()) {
					cid = infoList.get(i).getC_id().toString();
					amount = infoList.get(i).getC_value().toString();
				}
			}
			type= type_wx;
			getOrderData(cid,amount);}
			break;
		case R.id.ll_ali:
			{String cid = "";
			String amount = "";
			ArrayList<BuyData> infoList = adapter.getData();
			for (int i = 0; i < infoList.size(); i++) {
				if (infoList.get(i).isSelect()) {
					cid = infoList.get(i).getC_id().toString();
					amount = infoList.get(i).getC_value().toString();
				}
			}
			type= type_ali;
			getOrderData(cid,amount);}
			break;
		default:
			break;
		}
	}
}
